<?php
function alipay_config() {
	$cache_payment = cache::get('payment');
	$config = $cache_payment['alipay']['payment_config'];
	return $config;
}

//支付宝签名
function alipay_sign($arr) {
	global $pe;
	$config = alipay_config();
	//签名步骤一：拼接成字符串
	ksort($arr);
	foreach ($arr as $k => $v) {
		if ($k != "sign" && $v != ""){
			is_array($v) && $v = json_encode($v);
			$sign .= "{$k}={$v}&";
		}
	}
	$sign = trim($sign, "&");
	//签名步骤二：RSA加密    
    $key = $config['alipay_my_private_key'];
	if (stripos($key, '-----') !== false) {
		preg_match('|\-{5}[\s\S]*\-{5}([\s\S]*)\-{5}+[\s\S]*\-{5}|', $key, $match);
		$key = $match[1];
	}
	$key = str_replace(PHP_EOL, '', $key);
 	$key = "-----BEGIN RSA PRIVATE KEY-----\n".chunk_split($key, 64, "\n")."-----END RSA PRIVATE KEY-----\n";
    $res = openssl_get_privatekey($key);
    openssl_sign($sign, $sign_new, $res, OPENSSL_ALGO_SHA256);
    openssl_free_key($res);
	//base64编码
    $sign = base64_encode($sign_new);
    return $sign;
}

//支付宝退款
function alipay_refund($info) {
	global $pe, $db;
	$config = alipay_config();
	$order = $db->pe_select('order', array('order_id'=>$info['order_id']));
	$post['app_id'] = $config['alipay_appid'];
	$post['method'] = 'alipay.trade.refund';
	$post['format'] = 'JSON';
	$post['charset'] = 'utf-8';
	$post['sign_type'] = 'RSA2';
	$post['timestamp'] = date('Y-m-d H:i:s');
	$post['version'] = '1.0';
	$post['biz_content']['out_trade_no'] = $order['order_payid'];
	$post['biz_content']['refund_amount'] = $info['refund_money'];
	$post['biz_content']['out_request_no'] = $info['refund_id'];
	$post['biz_content'] = json_encode($post['biz_content']);
	$post['sign'] = alipay_sign($post);
	//发送post下单请求
	$json = pe_curl_post('https://openapi.alipay.com/gateway.do?charset=utf-8', $post);
	$json = json_decode(iconv('GB2312//IGNORE', 'UTF-8', $json), true);
	$json = $json['alipay_trade_refund_response'];
	if ($json['code'] == 10000) {
		$sql_set['refund_pstate'] = 'success';
		$sql_set['refund_presult'] = $msg = '';
		$code = 1;
	}
	else {
		$sql_set['refund_pstate'] = 'error';
		$sql_set['refund_presult'] = $msg = "{$json['msg']} - {$json['sub_code']} - {$json['sub_msg']}";
		$code = 0;
	}
	$sql_set['refund_outid'] = $json['trade_no'];
	$db->pe_update('refund', array('refund_id'=>$info['refund_id']), pe_dbhold($sql_set));
	return array('code'=>$code, 'msg'=>$msg);
}
